package controllers;

import is.ru.honn.rupin.data.PinDataGateway;
import is.ru.honn.rupin.data.UserDataGateway;
import is.ru.honn.rupin.domain.Board;
import is.ru.honn.rupin.domain.Pin;
import is.ru.honn.rupin.domain.User;
import is.ru.honn.rupin.domain.UserAuthentication;
import is.ru.honn.rupin.service.PinService;
import play.data.Form;
import play.mvc.Result;
import views.html.index;
import views.html.session.boardPage;
import views.html.session.frontPage;
import views.html.session.loginform;
import views.html.session.pinform;

import java.util.ArrayList;
import java.util.List;



/**
 * Created by: Sigrun Inga and Susanne
 * Date: 15.11.2012
 * Time: 10:30
 * Copyright (c) Sigrun Inga and Susanne Götz
 *
 * @author Sigrun Inga and Susanne Götz
 * @version 101.0
 */

/**
 * Session controller sér um alla vinnuna tendga innskráningu og pin adding
 *
 */
public class Session extends RuPinController {
    /**
     * Breytur
     */
    final static Form<UserAuthentication> loginForm = form(UserAuthentication.class);
    final static Form<Pin> addPinForm = form(Pin.class);
    public static User user = new User();
    public static UserAuthentication loggedIn = new UserAuthentication();
    /* Breytur end*/


    /**
     * Result loginForm() er að birta notandanum form til að geta loggað sig inn
     * þegar hann er nú þegar til í gagnagrunninum
     * @return  render loginForm
     */
    public static Result loginForm() {
        return ok(loginform.render(loginForm));
    }

    /**
     * Result login() nær í gögn úr loginForm, athugar ef username og password passa saman
     * og birtir pinnar þeirra sem notandinn fylgir á skjá
     * @return renders frontpage
     */
    public static Result login() {
        Form<UserAuthentication> filledForm = loginForm.bindFromRequest();

        if (filledForm.hasErrors()) {
            return badRequest(loginform.render(filledForm));
        }
        else
        {
            loggedIn = filledForm.get();

            UserDataGateway userDataGateway = (UserDataGateway) ctx.getBean("userDataGateway");
            user = userDataGateway.getUserByUsername(loggedIn.getUsername());

            PinService pinService = (PinService) ctx.getBean(("pinService"));

            if (user != null && loggedIn.getPassword().equals(user.getPassword())) {
                /* setja notandan í session*/
                session().put("username", loggedIn.getUsername());
                List<String> followers = userDataGateway.getFollowers(loggedIn.getUsername());

                List<Board> boards = new ArrayList<Board>();
                for (String f : followers) {

                    boards.addAll(pinService.getBoards(f));
                }
                for (Board b : boards) {
                    List<Pin> p = pinService.getPinsOnBoard(b.getName(), b.getCreator().getUsername());
                    b.setPins(p);
                }
                return ok(frontPage.render(boards));
            }
            else
            {
                filledForm.reject("password", "Username or password are incorrect");
                return badRequest(loginform.render(filledForm));
            }
        }
    }

    /**
     * Result boardView(...) verður kallað á ef notandinn smellir á board- link á frontpage
     * færibreytur koma inn í gegnum linkinn og í gegnum upplýsingar um innskráðan notanda.
     * @param boardname
     * @param username
     * @return  renders boardpage sem sýnir allar pinnar á völdu borði
     */
    public static Result boardView(String boardname, String username) {
        /* Tilraun til að gera check fyrir logIn session.
        session().get(loggedIn.getUsername()).equals(user.getUsername());*/
        PinService pinService = (PinService) ctx.getBean("pinService");
        Board b = (Board) pinService.getBoard(username, boardname);
        List<Pin> pins = pinService.getPinsOnBoard(b.getName(), username);

        return ok(boardPage.render(pins));
    }

    /**
     * Result pinForm() birtir form til að skrá nýjan pinna
     * @return  renders pinform
     */
    public static Result pinForm() {

        return ok(pinform.render(addPinForm));

    }

    /**
     * Result submit() sækir gögnin úr pinform og bætir nýjum pin inn í gagnagrunn
     * @return  renders boardpage með þessum nýja pinni
     */
    public static Result submit() {
        Form<Pin> filledForm = addPinForm.bindFromRequest();
        /* athugun ef innsláttur er í lagi */
        if (filledForm.field("description").value().length() < 1) {
            filledForm.reject("Description is needed");
        }

        if (filledForm.field("link").value().length() < 1 && filledForm.field("image").value().length() < 1) {
            filledForm.reject("please enter URL for link or image");
        }

        if (filledForm.field("boardname").value().length() < 1) {
            filledForm.reject("Please enter existing board name");
        }
        if (filledForm.hasErrors())
        {
            return badRequest(pinform.render(filledForm));
        }
        else
        {
            Pin pinCreated = filledForm.get();
            PinService pinService = (PinService) ctx.getBean("pinService");
            Board bord = pinService.getBoard(user.getUsername(), filledForm.field("boardname").value());

            Pin newPin = new Pin();
            newPin.setDescription(pinCreated.getDescription());
            newPin.setLink(pinCreated.getLink());
            newPin.setImage(pinCreated.getImage());
            PinDataGateway pinDataGateway = (PinDataGateway) ctx.getBean("pinDataGateway");
            pinDataGateway.add(newPin, bord.getName(), user.getUsername());
            /* setjum þennan nýja pin í Lista til að geta endurnýtt view "boardpage" */
            List<Pin> pins = new ArrayList<Pin>();
            pins.add(newPin);
            return ok(boardPage.render(pins));
        }
    }

    /**
     * Result logOut() loggar notandan út og hreinsar hann út úr session
     * @return  renders index
     */
    public static Result logOut(){
        session().clear();
        return ok(index.render());
    }

}
